<?php
namespace backend\controllers\rbac;
Use common\models\Admin;
use backend\controllers\BackendBase;
use common\models\AdminRole;
use common\models\RbacRole;
use yii\helpers\Json;

class AdminController extends BackendBase
{
    public function actionIndex(){
        if(!$this->isJson){
            return $this->renderView('/rbac/admin/index');
        }
        return $this->page( Admin::find() ) ;
    }


    public function actionRoles(){
        return RbacRole::find()->all() ;
    }


    public function actionSave(){
        $id = $this->request()->get('id',0);
        if(!$this->isPost){

            $data = '""' ;
            if($id){
                $data = Admin::find()->with('roles')->where(['id' => $id ])->asArray()->one() ;
                $data['roles'] = array_map(function($item){
                    return $item['role_id'] ;
                },$data['roles']);
                $data = Json::encode($data) ;

            }
            return $this->renderView('/rbac/admin/save',['data' => $data]);
        }

        $data = $this->request()->post() ;

        if($id){
            $model = Admin::findOne($id);
        }else{
            $model = new Admin();
            $model->generateAuthKey();
        }

        $model->username = $data['username'];
        $model->email = $data['email'];
        $data['password'] = trim($data['password']) ;
        if(!empty($data['password'])){
            $model->setPassword($data['password']);
        }

        if($model->save()){
            $model->saveRoles($data['roles']);
            return true ;
        }else{
            return $model->getErrors() ;
        }
    }


    public function actionDelete(){
        $id = $this->request()->get('id',0);
        $isDelete = Admin::findOne($id)->delete();
        return ['code' => 0];
    }
}